<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>卡片管理系统</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; background: #f5f5f5; display: flex; align-items: center; justify-content: center; min-height: 100vh; }
        .container { max-width: 1200px; width: 100%; margin: 20px auto; }
        .auth-container { max-width: 400px; margin: auto; }
        .header { background: white; padding: 20px; border-radius: 8px; margin-bottom: 20px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
        .header h1 { color: #333; margin-bottom: 10px; text-align: center; }
        .header .user-info { display: flex; align-items: center; gap: 15px; margin-top: 15px; }
        .header .user-info .avatar { width: 40px; height: 40px; border-radius: 50%; object-fit: cover; border: 2px solid #fff; }
        .header .points { background: #ff4757; color: white; padding: 5px 15px; border-radius: 20px; font-weight: bold; }
        .nav { display: flex; gap: 10px; margin-bottom: 20px; }
        .nav button { padding: 10px 20px; border: none; background: white; border-radius: 6px; cursor: pointer; transition: all 0.2s; }
        .nav button.active { background: #ff4757; color: white; }
        .nav button:hover:not(.active) { background: #f8f9fa; border-color: #ced4da; }
        .section { background: white; padding: 25px; border-radius: 8px; margin-bottom: 20px; box-shadow: 0 4px 12px rgba(0,0,0,0.05); }
        .section h2 { font-size: 22px; margin-bottom: 20px; border-bottom: 1px solid var(--border-color); padding-bottom: 10px; }
        .form-group { margin-bottom: 15px; }
        .form-group label { display: block; margin-bottom: 8px; font-weight: 600; color: #555; }
        .form-group input, .form-group textarea { width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px; font-size: 14px; }
        .form-group input:focus, .form-group textarea:focus { outline: none; border-color: #ff4757; }
        .btn { padding: 12px 24px; background: #ff4757; color: white; border: none; border-radius: 6px; cursor: pointer; font-size: 14px; transition: all 0.2s; }
        .btn:hover { background: #e84118; }
        .btn:disabled { background: #ccc; cursor: not-allowed; }
        .card-preview { border: 1px solid #ddd; border-radius: 8px; padding: 15px; background: #f9f9f9; margin-top: 15px; }
        .card-item { background: white; border-radius: 8px; padding: 15px; margin-bottom: 15px; box-shadow: 0 2px 5px rgba(0,0,0,0.1); }
        .card-item h3 { margin-bottom: 8px; color: #333; }
        .card-item .card-key { background: #f1f2f6; padding: 5px 10px; border-radius: 4px; font-family: monospace; margin: 5px 0; }
        .card-item .card-stats { color: #666; font-size: 12px; margin-top: 8px; }
        .card-item .card-actions { margin-top: 10px; }
        .card-item .btn-small { padding: 6px 12px; font-size: 12px; margin-right: 10px; }
        .alert { padding: 10px 15px; border-radius: 6px; margin-bottom: 15px; }
        .alert.success { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
        .alert.error { background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
        .hidden { display: none !important; }
        .loading { text-align: center; padding: 20px; color: #666; }
        .grid { display: grid; grid-template-columns: 1fr 300px; gap: 20px; }
        @media (max-width: 768px) { .grid { grid-template-columns: 1fr; } }
        .home-section { text-align: center; padding: 40px 20px; }
        .home-section .avatar-large { width: 120px; height: 120px; border-radius: 50%; object-fit: cover; margin-bottom: 20px; border: 4px solid #fff; box-shadow: 0 4px 15px rgba(0,0,0,0.1); }
        .home-section h2 { font-size: 28px; margin-bottom: 10px; }
        .home-section p { color: #666; }
    </style>
</head>
<body>
    <div class="container">
        <!-- 头部 -->
        <div id="main-header" class="header">
            <h1>卡片管理系统</h1>
            <div id="authSection" class="auth-container">
                <div id="loginForm">
                    <h3>登录</h3>
                    <div class="form-group">
                        <input type="text" id="loginUsername" placeholder="登录账号 / 邮箱" required autocomplete="username">
                    </div>
                    <div class="form-group">
                        <input type="password" id="loginPassword" placeholder="密码" required autocomplete="current-password">
                    </div>
                    <button type="button" class="btn" onclick="login()">登录</button>
                    <button type="button" class="btn" onclick="showRegister()" style="background: #5f27cd; margin-left: 10px;">注册</button>
                </div>
                
                <div id="registerForm" class="hidden">
                    <h3>注册</h3>
                    <div class="form-group">
                        <label>登录账号</label>
                        <input type="text" id="regUsername" placeholder="3-30位，仅限字母、数字和下划线" required>
                    </div>
                    <div class="form-group">
                        <label>用户名 (显示名称)</label>
                        <input type="text" id="regNickname" placeholder="在网站上显示的名称，支持中文" required>
                    </div>
                    <div class="form-group">
                        <label>邮箱</label>
                        <input type="email" id="regEmail" placeholder="用于找回密码" required>
                    </div>
                    <div class="form-group">
                        <label>密码</label>
                        <input type="password" id="regPassword" placeholder="至少6位" required>
                    </div>
                    <button type="button" class="btn" onclick="register()">注册</button>
                    <button type="button" class="btn" onclick="showLogin()" style="background: #5f27cd; margin-left: 10px;">返回登录</button>
                </div>
            </div>
            
            <div id="userInfo" class="user-info hidden">
                <img id="headerAvatar" src="/img/logo.png" alt="avatar" class="avatar">
                <span>欢迎，<strong id="userDisplayName"></strong></span>
                <div style="flex-grow: 1;"></div>
                <button type="button" class="btn" onclick="logout()" style="background: #666;">退出</button>
            </div>
        </div>

        <!-- 导航 -->
        <div id="navigation" class="nav hidden">
            <button id="nav-home" class="active" onclick="showSection('home')">首页</button>
            <button id="nav-create" onclick="showSection('create')">创建卡片</button>
            <button id="nav-cards" onclick="showSection('cards')">我的卡片</button>
            <button id="nav-transfer" onclick="showSection('transfer')">积分转赠</button>
            <button id="nav-profile" onclick="showSection('profile')">个人中心</button>
        </div>

        <!-- 消息提示 -->
        <div id="message" class="hidden"></div>

        <!-- 首页 -->
        <div id="homeSection" class="section hidden">
             <div class="home-section">
                <img id="homeAvatar" src="/img/logo.png" alt="avatar" class="avatar-large">
                <h2 id="welcomeMessage"></h2>
                <div class="user-stats-grid" style="display: flex; justify-content: center; gap: 20px; margin: 20px 0; flex-wrap: wrap;">
                    <div class="stat-card" style="background: #f9f9f9; padding: 15px 20px; border-radius: 8px; text-align: center;">
                        <span style="font-size: 14px; color: #666;">专属ID</span>
                        <p style="font-size: 20px; font-weight: bold; color: #333;" id="homeShortId">N/A</p>
                    </div>
                    <div class="stat-card" style="background: #f9f9f9; padding: 15px 20px; border-radius: 8px; text-align: center;">
                        <span style="font-size: 14px; color: #666;">当前积分</span>
                        <p style="font-size: 20px; font-weight: bold; color: #ff4757;" id="homePoints">0</p>
                    </div>
                    <div class="stat-card" style="background: #f9f9f9; padding: 15px 20px; border-radius: 8px; text-align: center;">
                        <span style="font-size: 14px; color: #666;">会员等级</span>
                        <p style="font-size: 20px; font-weight: bold; color: #333;" id="homeMemberLevel">普通会员</p>
                    </div>
                </div>
                <p>请开始一天的工作吧！</p>
            </div>
        </div>

        <!-- 创建卡片 -->
        <div id="createSection" class="section hidden">
            <div class="grid">
                <div>
                    <h2>创建卡片</h2>
                    <form id="createCardForm">
                        <div class="form-group">
                            <label>卡片标题 * <span style="color: #666; font-size: 12px;"></span></label>
                            <input type="text" id="cardTitle" placeholder="请输入商品标题，如：精选好物推荐" required>
                        </div>
                        <div class="form-group">
                            <label>标签文本 <span style="color: #666; font-size: 12px;"></span></label>
                            <input type="text" id="tagText" placeholder="如：官方专属、小红书官方卡片、限时优惠等">
                        </div>
                        <div class="form-group">
                            <label>副标题 <span style="color: #666; font-size: 12px;"></span></label>
                            <textarea id="description" placeholder="如：限时发放中、仅剩3件、热销中、限时特惠等" rows="2"></textarea>
                        </div>
                        <div class="form-group">
                            <label>图片链接 *</label>
                            <input type="url" id="cardImage" placeholder="请输入商品图片链接" required>
                        </div>
                        <div class="form-group">
                            <label>跳转链接 *</label>
                            <input type="url" id="targetUrl" placeholder="点击卡片后的跳转目标链接" required>
                        </div>
                        <div class="form-group">
                            <label>回调ID <span style="color: #666; font-size: 12px;">(高级选项，一般留空)</span></label>
                            <input type="text" id="callbackId" placeholder="留空则使用默认回调ID">
                        </div>
                        
                        <p style="color: #666; margin-bottom: 15px;">创建此卡片需要消耗 <strong id="createCost">100</strong> 积分</p>
                        <button type="submit" class="btn">创建卡片</button>
                    </form>
                </div>
                <div>
                    <h3>预览</h3>
                    <div class="card-preview" id="cardPreview">
                        <p style="color: #999;">填写信息后显示预览</p>
                    </div>
                </div>
            </div>
        </div>

        <!-- 我的卡片 -->
        <div id="cardsSection" class="section hidden">
            <h2>我的卡片</h2>
            <div id="cardsList" class="loading">加载中...</div>
        </div>

        <!-- 个人中心 -->
        <div id="profileSection" class="section hidden">
            <h2>个人中心</h2>
            <div id="membershipInfo" style="margin-bottom: 20px; background: #f9f9f9; padding: 15px; border-radius: 8px;">
                <!-- 会员信息将由JS填充 -->
                <p>我的专属ID: <strong id="memShortId"></strong> (转赠积分时使用)</p>
                <p>会员等级: <strong id="memLevel"></strong></p>
                <p>当前积分: <strong id="memPoints"></strong></p>
                <p id="nextLevelInfo"></p>
            </div>
            <div style="margin-bottom: 20px;">
                <h3>修改头像</h3>
                <div class="form-group">
                    <input type="file" id="avatarUpload" accept="image/jpeg, image/png, image/gif">
                </div>
                <button type="button" class="btn" onclick="uploadAvatar()">上传新头像</button>
            </div>
            <h3>修改密码</h3>
            <div class="form-group">
                <label>当前密码</label>
                <input type="password" id="currentPassword" placeholder="请输入当前密码">
            </div>
            <div class="form-group">
                <label>新密码</label>
                <input type="password" id="newPassword" placeholder="请输入新密码">
            </div>
            <button type="button" class="btn" onclick="changePassword()">修改密码</button>
        </div>

        <!-- 积分转赠 -->
        <div id="transferSection" class="section hidden">
            <h2>积分转赠</h2>
            <form id="transferForm">
                <div class="form-group">
                    <label>接收方专属ID</label>
                    <input type="text" id="recipientShortId" placeholder="请输入对方的3位数ID" required>
                </div>
                <div class="form-group">
                    <label>转赠积分数量</label>
                    <input type="number" id="transferAmount" placeholder="请输入正整数" required min="1">
                </div>
                <button type="submit" class="btn">确认转赠</button>
            </form>
        </div>
    </div>

    <script>
        let currentUser = null;
        let authToken = null;

        const sections = ['createSection', 'cardsSection', 'profileSection', 'loginRegisterSection'];
        const navButtons = ['nav-create', 'nav-cards', 'nav-profile'];

        const membershipConfig = {
            levels: { 1: '普通会员', 2: '银牌会员', 3: '金牌会员', 4: '钻石会员' },
            costs: { 1: 100, 2: 30, 3: 20, 4: 10 }
        };

        // 页面加载
        document.addEventListener('DOMContentLoaded', function() {
            authToken = localStorage.getItem('authToken');
            if (authToken) {
                checkAuth();
            }
            
            // 绑定表单事件
            document.getElementById('createCardForm').addEventListener('submit', createCard);
            
            // 预览更新
            ['cardTitle', 'tagText', 'cardImage', 'targetUrl', 'description', 'callbackId'].forEach(id => {
                document.getElementById(id).addEventListener('input', updatePreview);
            });

            document.getElementById('transferForm').addEventListener('submit', handleTransfer);
        });

        // 检查认证状态
        async function checkAuth() {
            try {
                const response = await fetch('/api/auth/me', {
                    headers: { 'Authorization': `Bearer ${authToken}` }
                });
                
                if (response.ok) {
                    currentUser = await response.json();
                    if (currentUser.role === 'admin') {
                        window.location.href = '/admin.html';
                        return;
                    }
                    updateLoggedInUI(currentUser);
                } else {
                    logout();
                }
            } catch (error) {
                logout();
            }
        }

        // 显示主应用
        function updateLoggedInUI(user) {
            currentUser = user;
            
            // 恢复页面正常布局
            document.querySelector('body').style.alignItems = 'flex-start';
            document.getElementById('main-header').classList.remove('auth-container');

            document.getElementById('authSection').classList.add('hidden');
            document.getElementById('userInfo').classList.remove('hidden');
            document.getElementById('navigation').classList.remove('hidden');
            
            const avatarUrl = user.avatarUrl || '/img/logo.png';
            const memberLevelText = membershipConfig.levels[user.membershipLevel] || '未知';

            // 填充简化的顶部栏信息
            document.getElementById('headerAvatar').src = avatarUrl;
            document.getElementById('userDisplayName').textContent = user.nickname;

            // 填充首页的详细信息
            document.getElementById('homeAvatar').src = avatarUrl;
            document.getElementById('welcomeMessage').textContent = `欢迎，${user.nickname}`;
            document.getElementById('homeShortId').textContent = user.shortId || 'N/A';
            document.getElementById('homePoints').textContent = user.points;
            document.getElementById('homeMemberLevel').textContent = memberLevelText;
            
            showSection('home');
        }

        // 显示注册表单
        function showRegister() {
            document.getElementById('loginForm').classList.add('hidden');
            document.getElementById('registerForm').classList.remove('hidden');
        }

        // 显示登录表单
        function showLogin() {
            document.getElementById('registerForm').classList.add('hidden');
            document.getElementById('loginForm').classList.remove('hidden');
        }

        // 登录
        async function login() {
            const username = document.getElementById('loginUsername').value;
            const password = document.getElementById('loginPassword').value;

            if (!username || !password) {
                showMessage('请填写用户名和密码', 'error');
                return;
            }

            try {
                const response = await fetch('/api/auth/login', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ username, password })
                });

                const data = await response.json();

                if (response.ok) {
                    authToken = data.token;
                    currentUser = data.user;
                    localStorage.setItem('authToken', authToken);
                    
                    if (currentUser.role === 'admin') {
                        window.location.href = '/admin.html';
                        return;
                    }

                    updateLoggedInUI(currentUser);
                    showMessage('登录成功！', 'success');
                } else {
                    showMessage(data.error, 'error');
                }
            } catch (error) {
                showMessage('网络错误，请稍后重试', 'error');
            }
        }

        // 注册
        async function register() {
            const username = document.getElementById('regUsername').value;
            const nickname = document.getElementById('regNickname').value;
            const email = document.getElementById('regEmail').value;
            const password = document.getElementById('regPassword').value;

            if (!username || !nickname || !email || !password) {
                showMessage('请填写所有字段', 'error');
                return;
            }

            try {
                const response = await fetch('/api/auth/register', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ username, nickname, email, password })
                });

                const data = await response.json();

                if (response.ok) {
                    authToken = data.token;
                    currentUser = data.user;
                    localStorage.setItem('authToken', authToken);
                    updateLoggedInUI(currentUser);
                    showMessage('注册成功！', 'success');
                } else {
                    showMessage(data.error, 'error');
                }
            } catch (error) {
                showMessage('网络错误，请稍后重试', 'error');
            }
        }

        // 退出登录
        function logout() {
            authToken = null;
            currentUser = null;
            localStorage.removeItem('authToken');
            
            document.querySelector('body').style.alignItems = 'center'; // 登录页垂直居中
            document.getElementById('main-header').classList.add('auth-container');
            document.getElementById('authSection').classList.remove('hidden');
            document.getElementById('userInfo').classList.add('hidden');
            document.getElementById('navigation').classList.add('hidden');
            document.getElementById('createSection').classList.add('hidden');
            document.getElementById('cardsSection').classList.add('hidden');
            document.getElementById('profileSection').classList.add('hidden');
            document.getElementById('userActions').classList.add('hidden');
            
            sections.forEach(id => {
                if(id !== 'loginRegisterSection') {
                    document.getElementById(id).classList.add('hidden');
                }
            });
        }

        // 显示页面
        function showSection(section) {
            document.querySelectorAll('.section').forEach(s => s.classList.add('hidden'));
            document.querySelectorAll('.nav button').forEach(b => b.classList.remove('active'));
            
            const buttonId = `nav-${section}`;
            const buttonEl = document.getElementById(buttonId);
            if (buttonEl) {
                buttonEl.classList.add('active');
            }
            
            document.getElementById(section + 'Section').classList.remove('hidden');
            
            if (section === 'cards') {
                loadMyCards();
            } else if (section === 'create') {
                updateCreateCost();
            } else if (section === 'profile') {
                displayMembershipInfo();
            }
        }

        // 更新创建卡片的积分消耗
        function updateCreateCost() {
            if (currentUser) {
                const cost = membershipConfig.costs[currentUser.membershipLevel] || 100;
                document.getElementById('createCost').textContent = cost;
            }
        }

        // 显示会员信息
        function displayMembershipInfo() {
            if (!currentUser) return;

            const levels = membershipConfig.levels;
            const costs = membershipConfig.costs;
            
            document.getElementById('memShortId').textContent = currentUser.shortId || '生成中...';
            document.getElementById('memLevel').textContent = levels[currentUser.membershipLevel];
            document.getElementById('memPoints').textContent = currentUser.points;

            const nextLevel = currentUser.membershipLevel + 1;
            const nextLevelCost = costs[nextLevel];
            const nextLevelName = levels[nextLevel];
            
            if (nextLevelName && typeof nextLevelCost !== 'undefined') {
                document.getElementById('nextLevelInfo').textContent = `下一等级 (${nextLevelName}) 创建卡片消耗: ${nextLevelCost} 积分`;
            } else {
                document.getElementById('nextLevelInfo').textContent = '您已达到最高会员等级！';
            }
        }

        // 创建卡片
        async function createCard(event) {
            event.preventDefault();
            const cardData = {
                title: document.getElementById('cardTitle').value,
                tagText: document.getElementById('tagText').value,
                imageUrl: document.getElementById('cardImage').value,
                targetUrl: document.getElementById('targetUrl').value,
                description: document.getElementById('description').value,
                callbackId: document.getElementById('callbackId').value
            };

            if (!cardData.title || !cardData.imageUrl || !cardData.targetUrl) {
                showMessage('请填写所有必填项', 'error');
                return;
            }

            try {
                const response = await fetch('/api/cards', {
                    method: 'POST',
                    headers: { 
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${authToken}`
                    },
                    body: JSON.stringify(cardData)
                });

                const result = await response.json();

                if (response.ok) {
                    showMessage(`卡片创建成功！卡密: ${result.cardKey}`, 'success');
                    document.getElementById('createCardForm').reset();
                    updatePreview(); // 清空预览
                    
                    // 更新用户信息（积分等）
                    checkAuth();

                } else {
                    showMessage(result.error || '创建失败', 'error');
                }
            } catch (error) {
                showMessage('请求失败，请检查网络', 'error');
            }
        }

        // 转赠积分
        async function handleTransfer(event) {
            event.preventDefault();
            const recipientId = document.getElementById('recipientShortId').value;
            const amount = parseInt(document.getElementById('transferAmount').value, 10);

            if (!recipientId || !/^\d{3}$/.test(recipientId)) {
                showMessage('请输入一个有效的3位数专属ID', 'error');
                return;
            }

            if (!amount || amount <= 0) {
                showMessage('请填写有效的积分数量', 'error');
                return;
            }

            if (!confirm(`确定要向ID为 ${recipientId} 的用户转赠 ${amount} 积分吗？`)) {
                return;
            }
            
            try {
                const response = await fetch('/api/users/transfer', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${authToken}`
                    },
                    body: JSON.stringify({ recipientShortId: parseInt(recipientId, 10), amount: amount })
                });

                const result = await response.json();

                if (response.ok) {
                    showMessage(result.message, 'success');
                    // 更新前端显示的用户积分
                    currentUser.points = result.remainingPoints;
                    document.getElementById('homePoints').textContent = result.remainingPoints;
                    document.getElementById('memPoints').textContent = result.remainingPoints;
                    // 清空表单
                    document.getElementById('transferForm').reset();
                } else {
                    showMessage(result.error || '转赠失败', 'error');
                }

            } catch (error) {
                showMessage('请求失败，请检查网络', 'error');
            }
        }

        // 复制到剪贴板
        function copyToClipboard(text) {
            if (navigator.clipboard) {
                navigator.clipboard.writeText(text).then(() => {
                    showMessage('已复制到剪贴板', 'success');
                });
            } else {
                // 兼容旧浏览器
                const textArea = document.createElement('textarea');
                textArea.value = text;
                document.body.appendChild(textArea);
                textArea.select();
                document.execCommand('copy');
                document.body.removeChild(textArea);
                showMessage('已复制到剪贴板', 'success');
            }
        }

        // 加载我的卡片
        async function loadMyCards() {
            try {
                const response = await fetch('/api/cards/my', {
                    headers: { 'Authorization': `Bearer ${authToken}` }
                });

                const data = await response.json();

                if (response.ok) {
                    displayCards(data.cards);
                } else {
                    document.getElementById('cardsList').innerHTML = '<p>加载失败</p>';
                }
            } catch (error) {
                document.getElementById('cardsList').innerHTML = '<p>网络错误</p>';
            }
        }

        // 显示卡片列表
        function displayCards(cards) {
            const container = document.getElementById('cardsList');
            
            if (cards.length === 0) {
                container.innerHTML = '<p style="color: #999; text-align: center; padding: 40px;">暂无卡片，快去创建第一张卡片吧！</p>';
                return;
            }

            container.innerHTML = cards.map(card => `
                <div class="card-item">
                    <div style="display: flex; align-items: center; gap: 15px;">
                        <img src="${card.imageUrl}" style="width: 80px; height: 80px; object-fit: cover; border-radius: 6px;" 
                             onerror="this.src=''">
                        <div style="flex: 1;">
                            <h3 style="margin: 0 0 5px 0;">${card.title}</h3>
                            <div class="card-key" style="margin: 5px 0;">卡密: ${card.cardKey}</div>
                            ${card.tagText ? `<p style="margin: 5px 0; color: #ff4757;"><strong>标签:</strong> ${card.tagText}</p>` : ''}
                            <p style="margin: 5px 0; color: #666; font-size: 12px;"><strong>跳转:</strong> ${card.targetUrl}</p>
                            <div class="card-stats">
                                点击次数: ${card.clickCount} | 创建时间: ${new Date(card.createdAt).toLocaleString()}
                            </div>
                        </div>
                    </div>
                    <div class="card-actions" style="margin-top: 15px;">
                        <button class="btn btn-small" onclick="copyCardKey('${card.cardKey}')">复制卡密</button>
                        <button class="btn btn-small" onclick="previewCard('${card.cardKey}')" style="background: #5f27cd;">预览</button>
                        <button class="btn btn-small" onclick="deleteCard(${card.id})" style="background: #e74c3c;">删除</button>
                    </div>
                </div>
            `).join('');
        }

        // 复制卡密
        function copyCardKey(cardKey) {
            copyToClipboard(cardKey);
        }

        // 预览卡片
        async function previewCard(cardKey) {
            try {
                const response = await fetch(`/api/hook/preview/${cardKey}`);
                const data = await response.json();
                
                if (response.ok) {
                    const modal = document.createElement('div');
                    modal.style.cssText = `
                        position: fixed; top: 0; left: 0; width: 100%; height: 100%; 
                        background: rgba(0,0,0,0.5); display: flex; align-items: center; 
                        justify-content: center; z-index: 1000;
                    `;
                    modal.innerHTML = `
                        <div style="background: white; padding: 30px; border-radius: 12px; max-width: 400px; width: 90%;">
                            <h3 style="margin-bottom: 15px;">卡片预览</h3>
                            <img src="${data.image}" style="width: 100%; height: 200px; object-fit: cover; border-radius: 8px; margin-bottom: 15px;">
                            <h4>${data.title}</h4>
                            <p style="color: #ff4757; margin: 5px 0;">${data.tagText || '小红书官方卡片'}</p>
                            <p style="margin: 10px 0;"><strong>跳转链接:</strong> ${data.link}</p>
                            ${data.description ? `<p style="color: #666; margin: 5px 0;">${data.description}</p>` : ''}
                            <p style="color: #999; font-size: 12px;">点击次数: ${data.clickCount}</p>
                            <button onclick="this.parentElement.parentElement.remove()" 
                                    style="margin-top: 15px; padding: 8px 16px; background: #ff4757; color: white; border: none; border-radius: 4px; cursor: pointer;">
                                关闭
                            </button>
                        </div>
                    `;
                    document.body.appendChild(modal);
                    modal.onclick = (e) => {
                        if (e.target === modal) modal.remove();
                    };
                } else {
                    showMessage('预览失败', 'error');
                }
            } catch (error) {
                showMessage('网络错误', 'error');
            }
        }

        // 删除卡片
        async function deleteCard(cardId) {
            if (!confirm('确定要删除此卡片吗？')) return;

            try {
                const response = await fetch(`/api/cards/${cardId}`, {
                    method: 'DELETE',
                    headers: { 'Authorization': `Bearer ${authToken}` }
                });

                if (response.ok) {
                    showMessage('卡片删除成功', 'success');
                    loadMyCards();
                } else {
                    showMessage('删除失败', 'error');
                }
            } catch (error) {
                showMessage('网络错误', 'error');
            }
        }

        // 修改密码
        async function changePassword() {
            const currentPassword = document.getElementById('currentPassword').value;
            const newPassword = document.getElementById('newPassword').value;

            if (!currentPassword || !newPassword) {
                showMessage('请填写当前密码和新密码', 'error');
                return;
            }

            try {
                const response = await fetch('/api/auth/change-password', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${authToken}`
                    },
                    body: JSON.stringify({ currentPassword, newPassword })
                });

                const data = await response.json();

                if (response.ok) {
                    showMessage('密码修改成功', 'success');
                    document.getElementById('currentPassword').value = '';
                    document.getElementById('newPassword').value = '';
                } else {
                    showMessage(data.error, 'error');
                }
            } catch (error) {
                showMessage('网络错误，请稍后重试', 'error');
            }
        }

        // 更新预览
        function updatePreview() {
            const title = document.getElementById('cardTitle').value || '点击获取联系方式';
            const tagText = document.getElementById('tagText').value || '小红书官方卡片';
            const imageUrl = document.getElementById('cardImage').value;
            const targetUrl = document.getElementById('targetUrl').value;
            const description = document.getElementById('description').value || '';
            const callbackId = document.getElementById('callbackId').value;

            const imageHtml = imageUrl ? 
                `<img src="${imageUrl}" style="width: 100%; height: 100%; object-fit: cover; border-radius: 6px;" 
                      onerror="this.src=''">` :
                `<div style="width: 100%; height: 100%; background: #f0f0f0; border-radius: 6px; display: flex; align-items: center; justify-content: center; color: #999; font-size: 12px;">图片</div>`;

            const descriptionHtml = description ? `<p style="color: #999; font-size: 11px; margin-top: 5px; line-height: 1.3;">${description}</p>` : '';

            document.getElementById('cardPreview').innerHTML = `
                <div style="display: flex; align-items: center; gap: 15px;">
                    <div style="flex-shrink: 0; width: 80px; height: 80px;">
                        ${imageHtml}
                    </div>
                    <div style="flex-grow: 1;">
                        <h4 style="margin-bottom: 5px; font-size: 16px; font-weight: 600;">${title}</h4>
                        <p style="color: #ff4757; font-size: 12px; margin-bottom: 8px; font-weight: bold;">${tagText}</p>
                        ${descriptionHtml}
                    </div>
                </div>
            `;
        }

        // 显示消息
        function showMessage(message, type) {
            const messageEl = document.getElementById('message');
            messageEl.className = `alert ${type}`;
            messageEl.textContent = message;
            messageEl.classList.remove('hidden');
            
            setTimeout(() => {
                messageEl.classList.add('hidden');
            }, 3000);
        }

        // 头像上传
        async function uploadAvatar() {
            const fileInput = document.getElementById('avatarUpload');
            const file = fileInput.files[0];
            if (!file) {
                showMessage('请先选择一个文件', 'error');
                return;
            }

            const formData = new FormData();
            formData.append('avatar', file);

            try {
                const response = await fetch('/api/users/avatar', {
                    method: 'POST',
                    headers: { 'Authorization': `Bearer ${authToken}` },
                    body: formData
                });

                const result = await response.json();

                if (response.ok) {
                    showMessage('头像更新成功！', 'success');
                    // Update UI immediately
                    document.getElementById('headerAvatar').src = result.avatarUrl;
                    document.getElementById('homeAvatar').src = result.avatarUrl;
                    currentUser.avatarUrl = result.avatarUrl; // Update local user object
                    fileInput.value = ''; // Clear file input
                } else {
                    showMessage(result.error || '上传失败', 'error');
                }
            } catch (error) {
                showMessage('请求失败，请检查网络', 'error');
            }
        }
    </script>
</body>
</html> 